<?php

/**
 * Undocumented class.
 */
class CombinationHelper
{
    public static function factorial($n)
    {
        return array_product(range(1, $n));
    }

    public static function arragementNum($n, $m)
    {
        return factorial($n) / factorial($n - $m);
    }

    public static function combinationNum($n, $m)
    {
        return arragementNum($n, $m) / factorial($m);
    }

    public static function arragement($array, $m)
    {
        $r = array();
        $n = count($array);
        if ($m <= 0 || $m > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; ++$i) {
            $b = $array;
            $t = array_splice($b, $i, 1);
            if (1 == $m) {
                $r[] = $t;
            } else {
                $c = arragement($b, $m - 1);
                foreach ($c as $v) {
                    $r = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

    public static function combination($array, $m)
    {
        $r = array();
        $n = count($array);
        if ($m <= 0 || $m > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; ++$i) {
            $t = array($array[$i]);
            if (1 == $m) {
                $r[] = $t;
            } else {
                $b = array_slice($array, $i + 1);
                $c = combination($b, $m - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }
}
